package com.ruoyi.web.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.web.domain.WorkEnterprise;
import com.ruoyi.web.domain.WorkForm;
import com.ruoyi.web.domain.WorkFormAttachment;
import com.ruoyi.web.domain.dto.FormExportFilterDto;
import com.ruoyi.web.domain.dto.WorkFormDto;
import com.ruoyi.web.domain.dto.WorkFormExportDto;
import com.ruoyi.web.domain.export.WorkFormExport;
import com.ruoyi.web.handler.HeaderStyleHandler;
import com.ruoyi.web.service.WorkEnterpriseService;
import com.ruoyi.web.service.WorkFormAttachmentService;
import com.ruoyi.web.service.WorkFormService;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 工单表 前端控制器
 * </p>
 *
 * @author 
 * @since 2025-03-10
 */
@RestController
@RequestMapping("/work-form")
public class WorkFormController extends BaseController {

    @Autowired
    private WorkFormService workFormService;

    @Autowired
    private WorkFormAttachmentService workFormAttachmentService;

    @Autowired
    private WorkEnterpriseService workEnterpriseService;

    @ApiOperation("信息组申请表单提交")
    @PostMapping("/infoDept/apply")
    public AjaxResult infoDeptApply(@RequestBody WorkFormDto dto){
        workFormService.infoDeptApply(dto);
        return AjaxResult.success();
    }

    /**
     * 目前用于诉求反馈质量分级的更新、诉求备注的更新
     */
    @ApiOperation("更新诉求字段值（通用）")
    @PutMapping
    public AjaxResult updateWorkForm(@RequestBody WorkFormDto dto){
        workFormService.updateWorkForm(dto);
        return AjaxResult.success();
    }

    /**
     * 转交
     */
    @ApiOperation("市级账号将诉求批量指派至区县级账号")
    @PutMapping("/sendBatch")
    public AjaxResult sendBatch(@RequestBody WorkFormDto dto){
        workFormService.sendBatch(dto);
        return AjaxResult.success();
    }

    @ApiOperation("省级账号批量审核指派申请")
    @PutMapping("/reviewSending")
    public AjaxResult reviewSending(@RequestBody WorkFormDto dto){
        workFormService.reviewSending(dto);
        return AjaxResult.success();
    }

    @ApiOperation("对被指派来的诉求进行确认")
    @GetMapping("/confirmSent")
    public AjaxResult confirmSent(@RequestParam("baseId") String baseId){
        return workFormService.confirmSent(baseId);
    }

    @ApiOperation("综合组派单表单提交")
    @PutMapping("/generalDept/send")
    public AjaxResult generalDeptSend(@RequestBody WorkFormDto dto){
        workFormService.generalDeptSend(dto);
        return AjaxResult.success();
    }

    @ApiOperation("为诉求上传补充附件")
    @PostMapping("/uploadSupplement")
    public AjaxResult uploadSupplement(@RequestBody WorkFormDto dto){
        workFormService.uploadSupplement(dto);
        return AjaxResult.success();
    }

    @ApiOperation("查询表单详情")
    @GetMapping("/detail/{baseId}")
    public AjaxResult getDetail(@PathVariable("baseId") String baseId){
        return AjaxResult.success(workFormService.getDetail(baseId));
    }

    @ApiOperation("删除工单")
    @DeleteMapping("/{baseId}")
    public AjaxResult deleteById(@PathVariable("baseId") Long baseId){
        workFormAttachmentService.remove(new LambdaQueryWrapper<WorkFormAttachment>().eq(WorkFormAttachment::getFormId, baseId));
        workFormService.removeById(baseId);
        return AjaxResult.success();
    }

    @GetMapping("/list")
    public TableDataInfo list(WorkFormDto dto)
    {
        startPage();
        List<WorkForm> list = workFormService.workFormList(dto);
        return getDataTable(list);
    }

    //@PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "工单处理", businessType = BusinessType.UPDATE)
    @PutMapping("/deal")
    public AjaxResult selectAuthUserAll(@RequestBody WorkFormDto dto)
    {
        return toAjax(workFormService.dealWorkForm(dto));
    }

    @ApiOperation("导出工单数据")
    @GetMapping("/list/export")
    public AjaxResult exportWorkFormList(HttpServletResponse response, WorkFormDto dto) {
        try {
            List<WorkForm> workForms = workFormService.workFormList(dto);
            List<WorkFormExport> workFormExports = new ArrayList<>();
            for (WorkForm workForm : workForms) {
                WorkFormExport workFormExport = new WorkFormExport();
                BeanUtils.copyProperties(workForm, workFormExport);
                if (StringUtils.isNotBlank(workForm.getPolicyFormType())) {
                    workFormExport.setField(workForm.getPolicyFormType());
                } else {
                    workFormExport.setField(workForm.getSocialResourceType());
                }
                LocalDateTime completeTime = workForm.getCompleteTime();
                if (completeTime == null) {
                    workFormExport.setCompleteTimeStr("");
                } else {
                    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                    String format = completeTime.format(dateTimeFormatter);
                    workFormExport.setCompleteTimeStr(format);
                }
                if (workForm.getStatus() != null && workForm.getStatus() == 0) {
                    workFormExport.setStatusStr("未分配");
                } else if (workForm.getStatus() != null && workForm.getStatus() == 1) {
                    workFormExport.setStatusStr("进行中");
                } else if (workForm.getStatus() != null && workForm.getStatus() == 2) {
                    workFormExport.setStatusStr("已完成");
                } else {
                    workFormExport.setStatusStr("");
                }
                List<WorkEnterprise> enterpriseList = workEnterpriseService.list(new LambdaQueryWrapper<WorkEnterprise>().eq(WorkEnterprise::getCompanyName, workFormExport.getEnterpriseName()).orderByAsc(WorkEnterprise::getId));
                if (enterpriseList.size() == 1) {
                    workFormExport.setCompanyType(enterpriseList.get(0).getCompanyType());
                    workFormExport.setCompanyProp(enterpriseList.get(0).getCompanyProp());
                    workFormExport.setCompanyScale(enterpriseList.get(0).getCompanyScale());
                    workFormExport.setIndustryType(enterpriseList.get(0).getIndustryType());
                } else if (enterpriseList.size() > 1) {
                    // 筛选统一信用代码只包含大写字母与数字的
                    List<WorkEnterprise> collect = enterpriseList.stream().filter(i -> i.getUnicode().matches("[A-Z0-9]+")).collect(Collectors.toList());
                    if (collect.size() > 0) {
                        workFormExport.setCompanyType(collect.get(0).getCompanyType());
                        workFormExport.setCompanyProp(collect.get(0).getCompanyProp());
                        workFormExport.setCompanyScale(collect.get(0).getCompanyScale());
                        workFormExport.setIndustryType(collect.get(0).getIndustryType());
                    } else {
                        workFormExport.setCompanyType(enterpriseList.get(0).getCompanyType());
                        workFormExport.setCompanyProp(enterpriseList.get(0).getCompanyProp());
                        workFormExport.setCompanyScale(enterpriseList.get(0).getCompanyScale());
                        workFormExport.setIndustryType(enterpriseList.get(0).getIndustryType());
                    }
                }
                workFormExports.add(workFormExport);
            }

            // 设置响应头，确保浏览器以下载方式处理文件
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");

            // 设置文件名，注意需要对中文进行 URL 编码
            String fileName = URLEncoder.encode("诉求列表", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
                    "attachment; filename=\"" + fileName + ".xlsx\";" +
                            " filename*=UTF-8''" + fileName + ".xlsx");

            // 使用 EasyExcel 写入数据到输出流
            OutputStream outputStream =  response.getOutputStream();
            EasyExcel.write(outputStream, WorkFormExport.class)
                    .sheet("诉求列表")
                    .registerWriteHandler(new HeaderStyleHandler())
                    .doWrite(workFormExports);

            // 关闭流资源
            if (outputStream != null) {
                outputStream.close();
            }

            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("导出异常：===》" + e);
            return AjaxResult.error(e.getMessage());
        }
    }

//    @GetMapping("/document/export")
//    public void exportDocument(@Valid @ModelAttribute WorkFormExportDto dto, HttpServletResponse response) throws Exception {
//        String filename = "解决企业困难诉求.docx";
//        String encodedFilename = URLEncoder.encode(filename, StandardCharsets.UTF_8.toString()).replace("+", "%20");
//        response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
//        response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + encodedFilename);
//        OutputStream outputStream = response.getOutputStream();
//        workFormService.generateDocument(dto, outputStream);
//        outputStream.flush();
//    }

    @GetMapping("/document/export")
    public void exportDocument(@Valid @ModelAttribute WorkFormExportDto dto, HttpServletResponse response) throws Exception {
//        String filename = "解决企业困难诉求.docx";
//        String encodedFilename = URLEncoder.encode(filename, StandardCharsets.UTF_8.toString()).replace("+", "%20");
//        response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
//        response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + encodedFilename);
//        OutputStream outputStream = response.getOutputStream();
        workFormService.generateDocument(dto, response);
//        outputStream.flush();
    }

    @GetMapping("/statistic/export")
    public AjaxResult exportDocument(FormExportFilterDto dto) throws Exception {
        Map map = workFormService.workFormStatistic(dto);
        return AjaxResult.success(map);
    }

    @GetMapping("/dataStatistics")
    public AjaxResult dataStatistics() {
        Map<String, Long> resultMap = workFormService.dataStatistics();
        return AjaxResult.success(resultMap);
    }

    @PutMapping("/updateStatus")
    public AjaxResult updateStatus(@RequestBody WorkFormDto dto) {
        if (dto.getStatus() == null) {
            return AjaxResult.error("请选择要更新的服务状态");
        }
        if (!(dto.getStatus() == 0 || dto.getStatus() == 1 || dto.getStatus() == 2 || dto.getStatus() == 3)) {
            return AjaxResult.error("请选择正确的服务状态");
        }
        workFormService.updateStatus(dto);
        return AjaxResult.success("更新成功");
    }
}
